from rest_framework.permissions import BasePermission
from django.core.cache import cache
from apps.UserControl.models.permission import Permissions
from apps.UserControl.models.user import User


def get_permission_list(user):
    if user.is_superuser:
        perms_list = ['admin']
    else:
        # none创建一个基于model的空querySet
        perms = Permissions.objects.none()
        per = user.permission.all()
        # for i in per:
        perms = perms | per

        perms_list = perms.values_list('method', flat=True)
        perms_list = list(set(perms_list))
    cache.set(user.username + '__perms', perms_list, 60 * 60)
    return perms_list


class RbacPermission(BasePermission):
    """
    重写权限认证类
    """

    def has_permission(self, request, view):
        if not request.user:
            perms = ['visitor']
        else:
            # 从缓存获取
            perms = cache.get(request.user.username + '__perms')
        if not perms:
            # 将当前用户权限存入缓存
            perms = get_permission_list(request.user)
        if perms:
            if 'admin' in perms:
                return True
            elif not hasattr(view, 'perms_map'):
                return True
            else:
                perms_map = view.perms_map
                _method = request._request.method.lower()
                if perms_map:
                    for item in perms_map:
                        if item == _method or item == '*':
                            if perms_map[item] in perms or perms_map[item] == '*':
                                return True
                return False
        else:
            return False
